// pages/resume/resume.js
import WxValidate from '../../utils/WxValidate'
import WXBizDataCrypt from '../../utils/WXBizDataCrypt'

const APPID = 'wxae0baeb8652624e9'
const APPSECRET = '16583dbcf174df1a3c36fa1b35e91829'
const db = wx.cloud.database()
let _id = ''
let openid = ''
let ifPhotoChange = false

Page({
  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    region: "请选择省份和城市",
    address: "请选择现住址所在区域",
    education: "请选择",
    _education: 99,
    _eduIndex: [0, 0],
    _eduArray: [
      ["博士/博士在读（普博）", "博士/博士在读（直博）", "硕士/硕士在读", "本科/本科在读"],
      ["博士毕业", "博士五年级（及以上）", "博士四年级", "博士三年级", "博士二年级", "博士一年级"]
    ],
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    db.collection('resume').get().then((res) => {
      if (res.data.length > 0) {
        let data = res.data[0]
        _id = data._id
        openid = data._openid
        this.setData({
          ...data,
          loading: false,
        })
      } else {
        ifPhotoChange = true
        this._getOpenid()
        let data = wx.getStorageSync('resume')
        console.log(data)   // 可能会扫出别人的信息
        this.setData({
          ...data,
          loading: false,
        })
      }
    })
    this.getSessionKey()
    this.initValidate()
  },
  _getOpenid() {
    let temp = wx.getStorageSync('openid')
    if(temp) {
      openid = temp
    } else {
      let app = getApp()
      app.getOpenid().then((res) => {
        openid = res.openid
        wx.setStorageSync('openid', res.openid)
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  formSubmit(e) { //每天只能交一次,待完成
    let params = e.detail.value
    if(e.detail.target.id == 'submit') {
      if (!this.WxValidate.checkForm(params)) {
        const error = this.WxValidate.errorList[0]
        console.log(error)
        wx.lin.showToast({
          title: error.msg,
          icon: 'error'
        })
        return false
      }
      if (this._valPicker(params)) {
        this.setData({
          loading: true
        })
        this.uploadPhoto().then((photoRes) => {
          params = {
            ...params,
            ...photoRes,
            region: this.data.region,
            address: this.data.address,
            education: this.data.education,
            _education: this.data._education,
          }
          this.uploadInfo(params).then((res) => {
            console.log(res)
            ifPhotoChange = false
            wx.removeStorageSync('resume')
            wx.lin.showToast({
              title: '上传成功～',
              icon: 'success'
            })
            this.setData({
              loading: false
            })
          }).catch((err) => {
            wx.lin.showToast({
              title: '上传失败，请重试~',
              icon: "error"
            })
            this.setData({
              loading: false
            })
          })
        })
      } 
    } else {
      const child = this.selectComponent('#photo').data
      params = {
        ...params,
        region: this.data.region,
        address: this.data.address,
        education: this.data.education,
        _education: this.data._education,
        photo: child.images
      }
      wx.setStorageSync('resume', params)
      if(e.detail.target.id == 'save') {
        wx.lin.showToast({ 
          title: '暂存成功~',
          icon: "success"
        })
      } else {
        wx.navigateTo({
          url: `../teacher-detail/teacher-detail?flag=0`,
        })
      }
    }
  },
  uploadInfo(params) {
    return new Promise((resolve, reject) => {
      if (_id) {
        db.collection('resume').doc(_id).update({
          data: {
            ...params,
            _lastUpdateTime: db.serverDate()
          }
        }).then((res) => {
          resolve(res)
        }).catch((err) => {
          reject(err)
        })
      } else {
        db.collection('resume').add({
          data: {
            ...params,
            _createTime: db.serverDate()
          }
        }).then((res) => {
          _id = res._id
          resolve(res)
        }).catch((err) => {
          reject(err)
        })
      }
    })
  },
  photoChange() {
    ifPhotoChange = true
  },
  uploadPhoto() {
    return new Promise((resolve, reject) => {
      if (ifPhotoChange) {
        const child = this.selectComponent('#photo').data
        console.log(`resume/${openid}/photo.png`)
        if (child.images.length > 0) {
          wx.cloud.uploadFile({
            cloudPath: `resume/${openid}/photo.png`,
            filePath: child.images[0],
            success: (res) => {
              console.log(res.fileID)
              resolve({
                photo: [res.fileID]
              })
            },
            fail: (err) => {
              console.log(err)
              wx.lin.showToast({
                title: '上传照片失败，请检查照片网络情况或试图重新添加照片~',
                icon: "error"
              })
              this.setData({
                loading: false
              })
            }
          })
        } else {
          resolve({
            photo: []
          })
        }
      } else {
        resolve({})
      }
    })
  },
  getPhoneNumber(e) {
    let detail = e.detail
    if (detail.errMsg == "getPhoneNumber:ok") {
      this.getSessionKey(this.decryption, detail)
    }
  },
  decryption(detail) {
    let session_key = wx.getStorageSync('session_key')
    console.log(session_key)
    let pc = new WXBizDataCrypt(APPID, session_key)
    let data = pc.decryptData(detail.encryptedData, detail.iv)
    this.setData({
      phone: data.phoneNumber
    })
  },
  _login(callback, detail) {
    console.log('重新获取sessionKey')
    wx.login({
      success: (res) => {
        let code = res.code
        wx.request({
          url: `https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${APPSECRET}&js_code=${code}&grant_type=authorization_code`,
          method: 'GET',
          success: (res) => {
            wx.setStorageSync('session_key', res.data.session_key)
            if (callback) {
              callback(detail);
            }
          }
        })
      },
    })
  },
  getSessionKey(callback, detail) {
    wx.checkSession({
      success: (res) => {
        let session_key = wx.getStorageSync('session_key')
        if (session_key) {
          if (callback) {
            callback(detail);
          }
        } else {
          this._login(callback, detail)
        }
      },
      fail: () => {
        this._login(callback, detail)
      }
    })
  },
  initValidate() {
    const rules = {
      surname: {
        required: true,
        maxlength: 10
      },
      _name: {
        required: true,
        maxlength: 10
      },
      gender: {
        required: true
      },
      phone: {
        required: true
      },
      street: {
        required: true,
        maxlength: 100
      },
      scope: {
        required: true
      },
      performance: {
        required: true
      },
      introduction: {
        required: true
      },
      experience: {
        required: true
      },
      method: {
        required: true
      },
    }
    const messages = {
      surname: {
        required: '请填写姓氏',
        maxlength: '不得超过10个字符'
      },
      _name: {
        required: '请填写名字',
        maxlength: '不得超过10个字符'
      },
      gender: {
        required: '请选择性别'
      },
      phone: {
        required: '请提供此微信绑定的手机号码'
      },
      street: {
        required: '请填写现住址所在街道',
        maxlength: '不得超过100个字符'
      },
      scope: {
        required: '请填写擅长科目',
      },
      performance: {
        required: '请填写相关成绩',
      },
      introduction: {
        required: '请填写自我介绍',
      },
      experience: {
        required: '请填写家教经验',
      },
      method: {
        required: '请填写教学方法',
      },
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  bindRegionChange(e) {
    let value = e.detail.value
    switch (value[0]) {
      case "全部":
        wx.lin.showToast({
          title: "请选择省份",
          icon: 'error'
        })
        return
      case "北京市":
      case "天津市":
      case "上海市":
      case "重庆市":
      case "香港特别行政区":
      case "澳门特别行政区":
        this.setData({
          region: value[0]
        })
        return
    }
    if (value[1] == "全部") {
      wx.lin.showToast({
        title: "请选择城市",
        icon: 'error'
      })
      return
    }
    this.setData({
      region: value[0] + value[1]
    })
  },
  bindAddressChange(e) {
    let value = e.detail.value
    if (value[0] == "全部" || value[1] == "全部" || value[2] == "全部") {
      wx.lin.showToast({
        title: "请完整选择住址所在区域",
        icon: 'error'
      })
      return
    }
    switch (value[0]) {
      case "北京市":
      case "天津市":
      case "上海市":
      case "重庆市":
      case "香港特别行政区":
      case "澳门特别行政区":
        this.setData({
          address: value[0] + value[2]
        })
        break
      default:
        this.setData({
          address: value[0] + value[1] + value[2]
        })
        break
    }
  },
  bindEducationChange(e) {
    let value = e.detail.value
    console.log(value)
    this.setData({
      _education: value[0],
      education: this.data._eduArray[1][value[1]]
    })
  },
  bindMultiColumnChange(e) {
    let data = {
      _eduArray: this.data._eduArray,
      _eduIndex: this.data._eduIndex,
    }
    if (e.detail.column == 0) {
      data._eduIndex[0] = e.detail.value
      switch (e.detail.value) {
        case 0:
        case 1:
          data._eduArray[1] = ["博士毕业", "博士五年级（及以上）", "博士四年级", "博士三年级", "博士二年级", "博士一年级"]
          break
        case 2:
          data._eduArray[1] = ["硕士毕业", "硕士三年级", "硕士二年级", "硕士一年级"]
          break
        case 3:
          data._eduArray[1] = ["本科毕业", "大四", "大三", "大二", "大一"]
          break
      }
      data._eduIndex[1] = 0
      this.setData(data)
    }
  },
  _valPicker(params) {
    if (this.data.region == "请选择省份和城市") {
      wx.lin.showToast({
        title: "请填写籍贯",
        icon: 'error'
      })
      return false
    }
    if (this.data.address == "请选择现住址所在区域") {
      wx.lin.showToast({
        title: "请填写住址区域",
        icon: 'error'
      })
      return false
    }
    let flag = true
    switch (this.data._education) {
      case 99:
        flag = false
        break
      case 0:
        flag = params.schoolBac && params.schoolMas && params.schoolDoc &&
          params.majorBac && params.majorMas && params.majorDoc
        break
      case 1:
        flag = params.schoolBac && params.schoolDoc && params.majorBac && params.majorDoc
        break
      case 2:
        flag = params.schoolBac && params.schoolMas && params.majorBac && params.majorMas
        break
      case 3:
        flag = params.schoolBac && params.majorBac
        break
    }
    if (!flag) {
      wx.lin.showToast({
        title: "请完整填写学历信息",
        icon: 'error'
      })
      return false
    }
    return true
  },
  uploadCred() {
    if (!_id) {
      wx.lin.showToast({
        title: '请先提交完整版简历',
        icon: 'error'
      })
      return
    }
    const images = this.selectComponent('#cred').data.images
    if (images.length == 0) {
      wx.lin.showToast({
        title: '暂无可上传图片',
        icon: 'error'
      })
      return
    }
    wx.lin.showDialog({
      type:"confirm",     
      content:"身份验证只能提交一次",
      success: (res) => {
        if (res.confirm) {
          this.setData({
            loading: true
          })
          let promiseArr = []
          let fileIDs = []
          // 图片上传
          for (let i = 0, len = images.length; i < len; i++) {
            let p = new Promise((resolve, reject) => {
              wx.cloud.uploadFile({
                cloudPath: `resume/${openid}/credential-${i}.png`,
                filePath: images[i],
                success: (res) => {
                  console.log(res.fileID)
                  fileIDs = fileIDs.concat(res.fileID)
                  resolve()
                },
                fail: (err) => {
                  console.error(err)
                  reject()
                }
              })
            })
            promiseArr.push(p)
          }
          // 存入到云数据库
          Promise.all(promiseArr).then((res) => {
            db.collection('resume').doc(_id).update({
              data: {
                credential: fileIDs,
                ifCredential: true
              }
            }).then((res) => {
              this.setData({
                ifCredential: true,
                loading: false
              }, () => {
                wx.lin.showToast({
                  title: '上传成功～',
                  icon: 'success'
                })
              })
            }).catch((err) => {
              this.setData({
                loading: false
              })
              wx.lin.showToast({
                title: '上传失败，请重试～',
                icon: 'error'
              })
            })
          }).catch((err) => {
            this.setData({
              loading: false
            })
            wx.lin.showToast({
              title: '上传失败，请重试～',
              icon: 'error'
            })
          })
        }
      }
    })
  }
})